package com.kbt.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.android.volley.Request;
import com.google.gson.Gson;
import com.kbt.activity.R;
import com.kbt.activity.StoreActivity;
import com.kbt.adapter.GoodCarCompleteAdapter;
import com.kbt.base.BaseApplication;
import com.kbt.commont.Constants;
import com.kbt.model.data.*;
import com.kbt.model.holder.GoodForCompCarInfoHolder;
import com.kbt.net.RequestManager;
import com.kbt.util.data.StaticData;
import com.kbt.util.tool.CommonStatus;
import com.kbt.util.utils.LoadingDialog;
import com.kbt.util.utils.SharePreferenceUtils;
import com.kbt.util.utils.Utils;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @author zhgk
 * @package: com.kbt.fragment
 * @TODO: 购物车结算时的商品列表
 * @data: 2015/8/12 8:38
 * @version: V1.0
 */
public class GoodCarCompleteFragment extends Fragment implements RequestManager.ResponseInterface{
    //商品视图
    private ListView goodListView;
    //商品视图数据适配器
    private GoodCarCompleteAdapter adapter;

    private TextView totalView;

    private Button jsBtn;

    private TextView textView18;
    private TextView textView20;
    private TextView textV4iew21;
    private TextView fdhiew22;
    private TextView dfh;


    private RequestManager mRequestManager;
    private Map<String, Object> map =null;
    private Map<String,String> mappost =null;
    private ShopCarListBean shopCarListBean;
    private BaseBean baseBean;
    private List<ShopCarBean> shopCarBeans = new ArrayList<ShopCarBean>();
    private boolean ischeck =false;
    private SharePreferenceUtils share;
    private String phone;
    private LoadingDialog mProgress;
    //库存
    private List<KuCunBean> kuCunBeans = new ArrayList<KuCunBean>();
    private KuCunListBean kuCunListBean;
    private Map<String,String> kunCunMap = new HashMap<String,String>();

    /**
     * 加载good_car_complete 部局文件
     *
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.good_car_complete, container, false);
    }

    /*****
     * 重写启动方法 用于处理页面初始化等
     */
    @Override
    public void onStart() {
        super.onStart();
        mRequestManager = new RequestManager();
        mRequestManager.setResponseListener(this);
        map = new HashMap<String, Object>();
        mappost = new HashMap<String,String>();
        share = new SharePreferenceUtils(getActivity());
        phone = share.getString("user_mobile","");
        ischeck =false;
        //初始化底部按钮事件与金额
        initBottom();
        //初始化布局
        initListView();
        //获取数据
        getData();

    }
    //获取购物车数据
    private void getData(){
        showProgress();
        if(Utils.isNetworkAvailable(getActivity())) {
            mRequestManager.requestGet(Request.Method.GET, Constants.ServiceInterFace.selectShopCarURL + phone + "&methodType=queryGoodsList", Constants.RequestTag.selectShopCarTag, map, ShopCarListBean.class);
        }else{
            stopProgress();
            Toast.makeText(getActivity(),R.string.Wangluo,Toast.LENGTH_SHORT).show();
        }
    }

    /***
     * 初始化布局
     */
    private void initListView() {
        goodListView = (ListView) getView().findViewById(R.id.car_cp_goodListView);
        goodListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                GoodForCompCarInfoHolder viewHolder = (GoodForCompCarInfoHolder) view.getTag();
                if (shopCarBeans.get(position).getGoods_status().equals("0")) {
                    httpSelected(shopCarBeans.get(position).getGoods_id(), "1");
                    viewHolder.getGoodCheckBox().setChecked(true);
                    shopCarBeans.get(position).setGoods_status("1");

                    String price = viewHolder.getGoodPrice().getText() + "";
                    String count = viewHolder.getGoodCount().getText() + "";
                    BaseApplication.getInstance().shopCarTotal += Double.parseDouble(price) * Integer.parseInt(count);
                    BaseApplication.getInstance().shopCarNumber += Integer.parseInt(count);
                    textView20.setText(new DecimalFormat("#.##").format(BaseApplication.getInstance().shopCarTotal));
                    textView18.setText("已选择商品" + BaseApplication.getInstance().shopCarNumber + "件");
                } else {
                    httpSelected(shopCarBeans.get(position).getGoods_id(), "0");
                    viewHolder.getGoodCheckBox().setChecked(false);
                    shopCarBeans.get(position).setGoods_status("0");
                    String price = viewHolder.getGoodPrice().getText() + "";
                    String count = viewHolder.getGoodCount().getText() + "";
                    BaseApplication.getInstance().shopCarTotal -= Double.parseDouble(price) * Integer.parseInt(count);
                    BaseApplication.getInstance().shopCarNumber -= Integer.parseInt(count);
                    textView20.setText(new DecimalFormat("#.##").format(BaseApplication.getInstance().shopCarTotal));
                    textView18.setText("已选择商品" + BaseApplication.getInstance().shopCarNumber + "件");
                }
                double price = BaseApplication.getInstance().shopCarTotal - Double.parseDouble(textV4iew21.getText().toString()) + Double.parseDouble(fdhiew22.getText().toString());
                dfh.setText(new DecimalFormat("#.##").format(price));
                totalView.setText(new DecimalFormat("#.##").format(price));
                BaseApplication.getInstance().shopCarPayable = price;
            }
        });


        adapter = new GoodCarCompleteAdapter(getActivity(), shopCarBeans, totalView);
        goodListView.setAdapter(adapter);
    }
    private void httpSelected(String goods_id,String status){
        if(Utils.isNetworkAvailable(getActivity())) {
            Gson gson = new Gson();
            mappost.clear();
            mappost.put("methodType", "set_check");
            Map dataMap = new HashMap<String,String>();
            dataMap.put("user_mobile", phone);
            dataMap.put("goods_status", status);
            dataMap.put("goods_id", goods_id);
            mappost.put("data", gson.toJson(dataMap));
            mRequestManager.post(Constants.ServiceInterFace.shopCarSelectedURL, mappost, Constants.RequestTag.shopCarSelectedTag, BaseBean.class);
        }else{
            Toast.makeText(getActivity(),R.string.Wangluo,Toast.LENGTH_SHORT).show();
        }
    }


    /****
     * 初始化底部按钮
     */
    private void initBottom() {
        totalView = (TextView) getActivity().findViewById(R.id.car_cp_totalFee);
        textView18 =(TextView) getActivity().findViewById(R.id.textView18);
        textView20 = (TextView) getActivity().findViewById(R.id.textView20);
        textV4iew21 = (TextView) getActivity().findViewById(R.id.textV4iew21);
        fdhiew22 = (TextView) getActivity().findViewById(R.id.fdhiew22);
        dfh = (TextView) getActivity().findViewById(R.id.dfh);
        //要把从后台获取的商品运费和商品优惠给application，后边用到
        BaseApplication.getInstance().freight=0;
        BaseApplication.getInstance().discount=0;
        textView20.setText("0.0");
        dfh.setText("0.0");
        totalView.setText("0.0");
        textView18.setText("已选择商品"+0+"件");
        textV4iew21.setText("0.0");
        fdhiew22.setText("0.0");
        jsBtn = (Button) getActivity().findViewById(R.id.car_cp_jsbtn);
//        BtnSetting.setBtnBackground(jsBtn, 2, Color.RED, Color.RED, 5);


        jsBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for(int i=0;i<shopCarBeans.size();i++){
                    if(shopCarBeans.get(i).getGoods_status().equals("1")){
                        ischeck =true;
                    }
                }
                if(!ischeck){
                    Toast.makeText(getActivity(),"请选择您要购买的商品",Toast.LENGTH_SHORT).show();
                    return;
                }
              httpKuncun();
            }
        });

    }
    //查询库存
    private void httpKuncun(){
        String goods_id = "";
        for(int i=0;i<shopCarBeans.size();i++){
            if(shopCarBeans.get(i).getGoods_status().equals("1")) {
                goods_id += "\'" + shopCarBeans.get(i).getGoods_id() + "\'" + ",";
            }
        }
        showProgress();
        if(Utils.isNetworkAvailable(getActivity())) {
            mRequestManager.requestGet(Request.Method.GET, Constants.ServiceInterFace.selectKunCunURL + goods_id.substring(0,goods_id.length()-1), Constants.RequestTag.selectKunCunTag, map, KuCunListBean.class);
        }else{
            stopProgress();
            Toast.makeText(getActivity(),R.string.Wangluo,Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public <T> void successResponse(T parsedGSON, int tag) {
        stopProgress();
        if (tag == Constants.RequestTag.selectShopCarTag) {
            if (parsedGSON != null) {
                shopCarListBean = (ShopCarListBean) parsedGSON;
                // 判断是否是有数据
                if (shopCarListBean.getResult().equals("success")) {// 成功
                    if (shopCarListBean.getData().size() > 0) {//获取到数据
                        BaseApplication.getInstance().shopCarTotal =0;
                        BaseApplication.getInstance().shopCarNumber =0;
                        BaseApplication.getInstance().shopCarPayable =0;
                        BaseApplication.getInstance().freight =0;
                        BaseApplication.getInstance().discount =0;
                        for(int i=0;i<shopCarListBean.getData().size();i++){
                            if(shopCarListBean.getData().get(i).getGoods_status().equals("1")){
                                float new_price = shopCarListBean.getData().get(i).getGoods_new_price();
                                int count =Integer.parseInt(shopCarListBean.getData().get(i).getGoods_count());
                                BaseApplication.getInstance().shopCarTotal +=(new_price*count);
                                textView20.setText(new DecimalFormat("#.##").format(BaseApplication.getInstance().shopCarTotal)+"");//商品总价
                                BaseApplication.getInstance().shopCarPayable=BaseApplication.getInstance().shopCarTotal;
                                dfh.setText(new DecimalFormat("#.##").format(BaseApplication.getInstance().shopCarPayable)+"");//应付总价
                                totalView.setText(new DecimalFormat("#.##").format(BaseApplication.getInstance().shopCarPayable)+"");//实付款
                                BaseApplication.getInstance().shopCarNumber+=Integer.parseInt(shopCarListBean.getData().get(i).getGoods_count());
                                textView18.setText("已选择商品"+BaseApplication.getInstance().shopCarNumber+"件");
                            }
                        }

                        shopCarBeans = shopCarListBean.getData();
//                        initCheck();
                        adapter.setList(shopCarBeans);
                        adapter.notifyDataSetChanged();
                    } else {
//                        Toast.makeText(getActivity(), "没数据哦22", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
        if (tag == Constants.RequestTag.shopCarSelectedTag) {
            if (parsedGSON != null) {
                baseBean = (BaseBean) parsedGSON;
                // 判断是否是有数据
                if (baseBean.getResult().equals("success")) {// 成功
                }else{
                }
            }
        }
        if (tag == Constants.RequestTag.selectKunCunTag) {
            /** 判断返回值不为空 **/
            if (parsedGSON != null) {
                kuCunListBean = (KuCunListBean) parsedGSON;
                if(kuCunListBean.getResult().equals("success")){
                    if(kuCunListBean.getData().size()>0){
                        kuCunBeans = kuCunListBean.getData();
                        for(int i=0;i<kuCunBeans.size();i++){
                            kunCunMap.put(kuCunBeans.get(i).getGoods_id(),kuCunBeans.get(i).getStore_counts());
                        }
                        for(int i=0;i<shopCarBeans.size();i++){
                            if(shopCarBeans.get(i).getGoods_status().equals("1")){
                                if(Integer.parseInt(shopCarBeans.get(i).getGoods_count())>Integer.parseInt(kunCunMap.get(shopCarBeans.get(i).getGoods_id()))){
                                    ischeck =false;
                                    Toast.makeText(getActivity(), shopCarBeans.get(i).getGoods_title()+"库存不足!", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                            }
                        }
                        BaseApplication.getInstance().currentItem=StaticData.INDEX_CAR;
                        BaseApplication.getInstance().carStatus=StaticData.GOOD_CAR_COMPLETE;
                        CommonStatus.carStatus = StaticData.GOOD_CAR_COMPLETE;
                        Intent intent = new Intent(getActivity(),StaticData.GOOD_FOR_PAY_CLASS);
                        intent.putExtra("biaoji", "shopcar");
                        getActivity().startActivity(intent);
                        getActivity().finish();
                    }
                }
            }
        }

    }

    @Override
    public void errorResonse(String retmeg, int tag) {
        stopProgress();
       Toast.makeText(getActivity(),R.string.noWangluo,Toast.LENGTH_SHORT).show();
    }
    /**
     * progressDialog的展示
     */
    public void showProgress() {
        if (mProgress == null) {
            mProgress = new LoadingDialog(getActivity(),"");
            mProgress.setCancelable(true);
            mProgress.show();

        } else {
            if (mProgress.isShowing()) {
                stopProgress();
            } else {
                mProgress.show();
            }
        }
    }


    /**
     * progressDialog的消失
     */
    public void stopProgress() {
        if (mProgress != null) {
            mProgress.dismiss();
            mProgress = null;
        }
    }
}
